package com.leisure.controllers;

import com.leisure.pojo.Result;
import com.leisure.pojo.TUser;
import com.leisure.services.UserService;
import com.leisure.utils.JWTUtil;
import com.leisure.utils.MD5Util;
import com.leisure.utils.RSAUtil;
import com.leisure.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserController
 * Package: com.leisure.controller
 * Description:
 *
 * @Author: MyLeisureLife
 * @Date: 2024/6/5:01:04:55 星期三
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }


    private final UserService userService;

    /**
     * register
     * @param encryptUsername 接收的RSA加密用户名
     * @param encryptPassword 接受的RSA加密的密码
     * @return 注册
     * @throws UnsupportedEncodingException 编码异常
     */
    @PostMapping("/register")
    public Result register(String encryptUsername, String encryptPassword) throws UnsupportedEncodingException {

        @Pattern(regexp = "^\\S{5,16}$") String  username = RSAUtil.decryptByPrivateKey(encryptUsername);
        @Pattern(regexp = "^\\S{5,16}$") String  password = RSAUtil.decryptByPrivateKey(encryptPassword);

        // md5 加密用户名 和 密码
        String md5Username = MD5Util.getMD5String(username);
        String md5Password= MD5Util.getMD5String(password);

        System.out.println("注册接口开始了");
        //查询用户
        TUser user = userService.findByUserName(md5Username);
        if(user==null){
            //如果没有被占用
            //注册
            userService.register(md5Username, md5Password);
            return Result.success();
        }else {
            //占用
            return Result.error("用户名已被占用");
        }
        //注册
    }

    /**
     * login
     * @param encryptUsername 接收的RSA加密的用户名
     * @param encryptPassword 接收的RSA加密的密码
     * @return 登录结构
     */
    @PostMapping("/login")
    public Result<Object> login(String encryptUsername, String encryptPassword){

        String  username = RSAUtil.decryptByPrivateKey(encryptUsername);
        String  password = RSAUtil.decryptByPrivateKey(encryptPassword);
        // md5 加密用户名 和 密码
        String md5Username = MD5Util.getMD5String(username);
        String md5Password= MD5Util.getMD5String(password);


        //first:  Verify if the username exists
        TUser user = userService.findByUserName(md5Username);
        //second: The first step of verification is successful. Continue to verity the password.
        if (user != null){

            //fourth: Verify if the password is correct
            if (user.getPassword().equals(md5Password)){
                //fifth:  The fourth step of successful verification returns the JWT token
                //fifth one create JWT token
                Map<String, Object> payloads = new HashMap<>();
                payloads.put("id", user.getId());
                payloads.put("username", user.getUsername());
                String jwtToken = JWTUtil.genJWT(payloads);
                Map<String, String> token = new HashMap<>();
                token.put("token", jwtToken);
                //fifth two return JWT token
                return Result.success(token);
            }else {
                //sixth: The fourth step of verification fails and returns an error message
                return Result.error("Password error！");
            }

        }else {
            //third:  The first step of verification is fails and returns a username error message
            return Result.error("The username does not exist!");
        }

    }

    /**
     * get user info
     * @param token jwt token
     * @return TUser
     */
    @GetMapping("/info")
    public Result<TUser> getUserInfo(@RequestHeader(name = "Authorization") String token){
        //parse token get username
        Map<String, Object> objectMap = (Map<String, Object>)ThreadLocalUtil.get();

        String username = (String) objectMap.get("username");

        //Obtain user information though username
        TUser user = userService.findByUserName(username);

        return Result.success(user);
    }

    /**
     * 更新数据
     * @param user 用户数据
     * @return 测试结果
     */
    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody @Validated TUser user){
        userService.update(user);
        return Result.success();
    }

}
